package cn.itcast.web.controller.system;


import cn.itcast.domain.system.Dept;
import cn.itcast.domain.system.Role;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.DeptService;
import cn.itcast.service.system.RoleService;
import cn.itcast.service.system.UserService;
import cn.itcast.web.controller.BaseController;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/system/user")
@Slf4j
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 显示列表
     * @param pageNum
     * @param pageSize
     * @return
     */

    @RequestMapping("/list")
    @RequiresPermissions("用户管理")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize){
         String CompanyId = getLoginCompanyId();
        //调用service层
         PageInfo<User> pageInfo = userService.findByPage(CompanyId, pageNum, pageSize);
        request.setAttribute("pageInfo",pageInfo);

        return "system/user/user-list";
    }

    /**
     * 进入添加页面，显示下拉列表
     * @return
     */
    @RequestMapping("/toAdd")
    public String toAdd(Model model){
        //查询所有部门
         List<Dept> deptList = deptService.findAll(getLoginCompanyId());
        //保存到请求域
        model.addAttribute("deptList",deptList);
        return "system/user/user-add";
    }

    /**
     *
     */
    @RequestMapping("/edit")
    public String edit(User user){
        // 设置企业id、企业名称（后期再从登陆用户哪里获取）
        user.setCompanyId(getLoginCompanyId());
        user.setCompanyName(getLoginCompanyName());

        //根据id判断是添加还是修改
        if(StringUtils.isEmpty(user.getId())){
            //为空，是添加
            userService.save(user);
            // 添加用户成功，发送邮件
            if(user.getEmail()!=null && !"".equals(user.getEmail())){
               String to =  user.getEmail();
               //处理发送邮件的业务
                String subject = "新员工入职通知";
                String content = "欢迎你来到SaasExport大家庭，我们是一个充满激情的团队，不是996哦！";

                //发送消息
                Map<String, Object> map = new HashMap<>();
                map.put("to",to);
                map.put("subject",content);
                map.put("content",content);
                rabbitTemplate.convertAndSend("msg.email",map);
            }
        }else {
            //修改
            userService.update(user);
        }
        return "redirect:/system/user/list";
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(String id, Model model){
        //根据用户id查询用户信息
         User user = userService.findById(id);
        //根据企业id查询部门信息
         List<Dept> deptList = deptService.findAll(getLoginCompanyId());

         //保存查询结果
        model.addAttribute("user",user);
        model.addAttribute("deptList",deptList);
        //跳转到页面
        return "system/user/user-update";
    }

    @GetMapping("/delete")
    @ResponseBody
    public Map<String,Integer> delete(String id){
         HashMap<String, Integer> map = new HashMap<>();
         boolean flag = userService.delete(id);
         if(flag){
             //删除成功
             map.put("message",1);
         }else {
             //删除失败
             map.put("message",0);
         }
        return map;
    }

    @RequestMapping("/roleList")
    public String roleList(String id){
        //1.查找用户
         User user = userService.findById(id);

         //2.查询所有角色(需要企业id)
         List<Role> roleList = roleService.findAll(getLoginCompanyId());

         //3.查询用户已经拥有的角色(为了页面页面选中效果)
        List<Role> userRoleList =  roleService.findRoleByUserId(id);

        //4. 优化处理：定义一个字符串保存用户的所有角色id，页面判断是否选中用户
        String userRoleIds = "";
        if(userRoleList!=null && userRoleList.size()>0){
            for (Role role : userRoleList) {
                userRoleIds += role.getId()+",";
            }
        }

        //存储到域中
        request.setAttribute("user",user);
        request.setAttribute("roleList",roleList);
        request.setAttribute("userRoleIds",userRoleIds);

        return "system/user/user-role";
    }

    @RequestMapping("/changeRole")
    public String changeRole(String userId,String[] roleIds){
        userService.changeRole(userId,roleIds);
        return "redirect:/system/user/list";
    }

}
